package com.bruce.springai.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bruce.springai.dto.UserInfoDTO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import reactor.core.publisher.Flux;

import java.time.LocalDate;
import java.util.Map;

import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;


@RestController
@RequestMapping("/promt")
@Tag(name = "组装提示词",description = "组装提示词")
public class PromtProjectController {

    @Resource
    private DeepSeekChatModel deepSeekChatModel ;


    @Value("classpath:/prompts/my-prompt-template.txt")
    private org.springframework.core.io.Resource systemPromt ;


    @GetMapping("/chat")
    @Operation(summary = "简单聊天", description = "根据用户提供的message，组装提示词，再调用大模型")
    public String chat(@RequestParam(name = "message") String message) {

        /**
         * 组装提示词
         */

         PromptTemplate promptTemplate = new PromptTemplate("今天是{current_date}") ;
         Message cuMessage = promptTemplate.createMessage(Map.of("current_date",LocalDate.now())) ; // 给提示词中的占位词{current_date} 赋值
        
         UserMessage userMessage = UserMessage.builder().text(message).build() ;
         Prompt prompt = Prompt.builder().messages(userMessage,cuMessage).build() ;
         return deepSeekChatModel.call(prompt).getResult().getOutput().getText() ;
    }
    
    @PostMapping("/chatWithUserInfo")
    @Operation(summary = "简单聊天", description = "根据用户提供的message、用户名，组装提示词，再调用大模型")
    public Flux<String> chatWithUserInfo(@RequestBody UserInfoDTO userInfoDTO) {
        /**
         * 组装系统提示词，并给提示词中的参数赋值
         */
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPromt) ;
        Message systemMessage = systemPromptTemplate.createMessage(Map.of("userName",userInfoDTO.getUserName(),"age",userInfoDTO.getAge())) ; // 给系统消息中的占位符赋值

        /**
         * 组装LLM的提示词模板
         */
        Prompt prompt = Prompt.builder().messages(systemMessage).build() ;
        return deepSeekChatModel.stream(prompt).map(response -> (response.getResult() == null || response.getResult().getOutput() == null
        || response.getResult().getOutput().getText() == null) ? ""
                : response.getResult().getOutput().getText()) ;
    }

}
